<!-- 成交结算标准 - 新建编辑查看 -->
<template>
    <div class="marketSettlementStandardHandle">
        <el-breadcrumb v-if="!viewDetailReceiveId" separator="/" class="bread-title">
            <el-breadcrumb-item :to="{ path: '/marketSettlementStandard' }">市场结算标准</el-breadcrumb-item>
            <el-breadcrumb-item>{{typeMap[type]}}</el-breadcrumb-item>
        </el-breadcrumb>
        <div v-if="type === 'view'">
            <el-form label-width="120px" size="small">
                <el-form-item label="提取标准：">市场结算标准</el-form-item>
                <el-form-item label="佣金来源：">合作标签</el-form-item>
                <hr/>
                <el-form-item label="提取规则：">基数*比例</el-form-item>
                <el-form-item label="计提节点：">{{calcNodeList | calNodeFilter}}</el-form-item>
                <el-form-item label="计提基数：">{{['好生活总收入','好生活平台费'][extractBaseNum-1]}}</el-form-item>
            </el-form>
            <div class="levelList" v-if="dealRangeList[0].list.length">
                <div class="levelList-item" v-for="(item,key) in dealRangeList" :key="key">
                    <div class="tac">{{item.name}}</div>
                    <el-table
                            :data="item.list"
                            border
                            highlight-current-row
                            style="width: 500px;margin-top: 20px;">
                        <el-table-column
                                align="center"
                                property="content"
                                label="计提区间">
                        </el-table-column>
                        <el-table-column
                                property="calculateExtractProportion"
                                width="150"
                                align="center"
                                label="计提比例（%）">
                        </el-table-column>
                    </el-table>
                </div>
            </div>
        </div>
        <div v-else>
            <el-form label-width="120px" size="small">
                <el-form-item label="提取标准：">市场结算标准</el-form-item>
                <el-form-item label="佣金来源：">
                    <el-select v-model="projectValue" size="small" placeholder="请选择佣金来源">
                        <el-option
                                v-for="item in projectOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="提取规则：">
                    <el-radio :label="ruleValue" value="基数*比例">基数*比例</el-radio>
                </el-form-item>
                <el-form-item label="计提节点：">
                    <ul class="calc-node-list">
                        <li v-for="(item, index) in calcNodeList">
                            <i class="el-icon-circle-close calc-node-close" @click="removeCalcNode(index)"></i>
                            <div>
                                计提节点：
                                <el-select size="small" style="width: 120px;" v-model="item.calculateNode" placeholder="请选择节点">
                                    <el-option
                                            v-for="option in calcNodeOptions"
                                            :disabled="!!calcNodeList.find(calcNodeItem => calcNodeItem.calculateNode === option.value)"
                                            :key="option.value"
                                            :label="option.label"
                                            :value="option.value">
                                    </el-option>
                                </el-select>
                            </div>
                            <div class="mt20">
                                计提比例：
                                <el-input style="width: 100px;" v-model="item.calculateProportion" @input="rewireCalcNode(item.calculateProportion, index)" size="small" placeholder="请输入内容"></el-input>
                                %
                            </div>
                        </li>
                        <li class="calc-node-add"><i class="el-icon-circle-plus " @click="addCalcNode"></i></li>
                    </ul>
                </el-form-item>
                <el-form-item label="计提基数：">
                    <el-select size="small" v-model="extractBaseNum" placeholder="请选择计提基数">
                        <el-option
                                v-for="item in extractBaseNumOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="">
                    <el-button type="primary" @click="chooseInterval">选择区间标准</el-button>
                </el-form-item>
            </el-form>
            <div class="levelList" v-if="dealRangeList[0].list.length">
                <div class="levelList-item" v-for="(item,key) in dealRangeList" :key="key">
                    <div class="tac">{{item.name}}</div>
                    <el-table
                            :data="item.list"
                            border
                            highlight-current-row
                            style="width: 500px;margin-top: 20px;">
                        <el-table-column
                                align="center"
                                property="content"
                                label="计提区间">
                        </el-table-column>
                        <el-table-column
                                property="calculateExtractProportion"
                                width="150"
                                align="center"
                                label="计提比例（%）">
                            <template slot-scope="scope">
                                <el-input style="width: 100px;" v-model="scope.row.calculateExtractProportion" @input="rewriteNum(scope, key)" size="small"></el-input>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </div>
            <div style="text-align: center; margin-top: 100px; width:1000px;">
                <el-button size="small" type="primary" @click="save">保存</el-button>
                <el-button size="small" @click="returnList">取消</el-button>
            </div>
            <el-dialog
                    title="选择区间标准"
                    :visible.sync="selectDialogVisible"
                    width="50%">
                <div>
                    <el-row :span="24" :gutter="20">
                        <el-col :span="18">
                            <el-input
                                    placeholder="请输入内容"
                                    prefix-icon="el-icon-search"
                                    size="normal"
                                    clearable
                                    v-model="selectDialogInputValue">
                            </el-input>
                        </el-col>
                        <el-col :span="6">
                            <el-button size="normal" type="primary" @click="getRangeList">查询</el-button>
                        </el-col>
                    </el-row>
                    <div class="mt20" style="height: 300px; overflow: auto">
                        <div v-for="item in selectedIntervalList" class="selectedInterval-item">
                            <el-radio class="mt20" v-model="selectedIntervalValue" :label="item.id">
                                <div class="selectedInterval-item-row">标准名称：{{item.name}}</div>
                                <div class="selectedInterval-item-row">版本： {{item.version}}</div>
                                <div class="selectedInterval-item-row">创建时间：{{item.createTime}}</div>
                                <el-button type="text" class="viewDetail" @click="viewDetail(item.id)">查看详情</el-button>
                            </el-radio>
                        </div>
                    </div>
                </div>
                <span slot="footer" class="dialog-footer">
                    <el-button type="primary" @click="selectedInterval">选 择</el-button>
                    <el-button @click="clearIntervalList">取 消</el-button>
                </span>
            </el-dialog>

            <el-dialog
                    title="查看详情"
                    :visible.sync="viewDetailVisible"
                    width="540px">
                <div v-for="(item,key) in viewDetailList" :key="key">
                    <h2 class="tac mt20">{{item.name}}</h2>
                    <el-table
                            :data="item.list"
                            border
                            highlight-current-row
                            style="width: 500px;margin-top: 20px;">
                        <el-table-column
                                align="center"
                                property="content"
                                label="计提区间">
                        </el-table-column>
                    </el-table>
                </div>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="viewDetailVisible = false">取 消</el-button>
                </span>
            </el-dialog>

        </div>
    </div>
</template>

<script>
    import api from '@/api/apiPath'

    export default {
        name: "marketSettlementStandardHandle",
        data() {
            return {
                type: "",
                typeMap: {
                    new: '新建',
                    edit: '编辑',
                    view: '查看'
                },
                ruleValue: "基数*比例",
                projectValue: "合作标签",
                projectOptions: [
                    {
                        value: '合作标签',
                        label: '合作标签'
                    }
                ],
                dealRangeList: [
                    {
                        name: '普通',
                        list: []
                    },
                    {
                        name: '包销',
                        list: []
                    }
                ],
                calcNodeOptions: [
                    {
                        value: 1,
                        label: '认购'
                    },
                    {
                        value: 2,
                        label: '交易及佣金确认'
                    },
                    {
                        value: 3,
                        label: '回款'
                    },
                    {
                        value: 4,
                        label: '签约'
                    }
                ],

                extractBaseNum: '',
                extractBaseNumOptions: [
                    {
                        value: 1,
                        label: '好生活总收入'
                    },
                    {
                        value: 2,
                        label: '好生活平台费'
                    },
                ],
                selectDialogVisible: false,
                selectDialogInputValue: "",
                selectedIntervalValue: "",
                resValue: "",
                selectedIntervalList: [],

                //3.0
                calcNodeList: [
                    {
                        calculateNode: 1,
                        calculateProportion: ''
                    }
                ],
                viewDetailVisible: false,
                viewDetailList: []
            }
        },
        created() {
            this.type = this.$route.query.type;
            if (this.type !== 'new') {
                this.getSingleTransactionSettlement(this.$route.query.id)
            }
        },
        props: ['viewDetailReceiveId'],
        watch: {
            viewDetailReceiveId: {
                handler(id) {
                    if (id) {
                        setTimeout(() => {
                            this.type = 'view';
                        }, 30)
                        // 初始化一下
                        this.dealRangeList = [
                            {
                                name: '普通',
                                list: []
                            },
                            {
                                name: '包销',
                                list: []
                            }
                        ];
                        this.getSingleTransactionSettlement(id)
                    }
                },
                immediate: true
            }
        },
        filters: {
            calNodeFilter(list) {
                let arr = [];
                list.forEach((item) => {
                    arr.push(item.calculateNodeName + '-' + item.calculateProportion + '%')
                });
                return arr.join(';')
            }
        },
        methods: {
            chooseInterval() {
                this.selectDialogVisible = true;
                this.getRangeList()
            },

            rewriteNum(scope, index) {
                let subIndex = scope.$index;
                let value = scope.row.calculateExtractProportion;
                setTimeout(() => {
                    this.dealRangeList[index].list[subIndex].calculateExtractProportion = this.formatTwoDecimal(value, 100, true);
                }, 30)
            },

            formatTwoDecimal(value, maxNumber, isIncludeMax) {
                value = value.replace(/[^\d.]/g, '');
                value = value.replace(/\.{2,}/g, ".");
                value = value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
                value = value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');
                if (value.indexOf('.') < 0 && value != '') {
                    value = parseInt(value);
                }
                // 设置最大限制
                if (maxNumber) {
                    const bool = isIncludeMax ? +value >= maxNumber : +value > maxNumber;
                    if (bool) {
                        let valueString = String(value)
                        value = valueString.slice(0, valueString.length - 1)
                    }
                }
                return value
            },
            getRangeList() {
                this.axios.post(api.profitStandardSettingList, {
                    name: this.selectDialogInputValue
                }).then((res) => {
                    this.selectedIntervalList = res.data.data.data
                })
            },
            getRangeDetailList(id) {
                this.axios.post(api.profitStandardSettingDetail, {id: id}).then((res) => {
                    const data = res.data.data;
                    this.dealRangeList = [{name: '普通', list: []}, {name: '包销', list: []}]
                    data.forEach((item) => {
                        this.dealRangeList[item.labelType - 1].list.push(item);
                    })
                })
            },

            viewDetail(id) {
                this.axios.post(api.profitStandardSettingDetail, {id: id}).then((res) => {
                    const data = res.data.data;
                    this.viewDetailList = [{name: '普通', list: []}, {name: '包销', list: []}]
                    data.forEach((item) => {
                        this.viewDetailList[item.labelType - 1].list.push(item);
                    })
                    this.viewDetailVisible = true;
                })
            },
            selectedInterval() {
                if (this.selectedIntervalValue) {
                    this.resValue = this.selectedIntervalValue;
                    this.getRangeDetailList(this.selectedIntervalValue);
                    this.clearIntervalList();
                } else {
                    this.$message({
                        message: '请选择区间标准！',
                        type: 'warning'
                    });
                    return false;
                }
            },
            clearIntervalList() {
                this.selectDialogVisible = false;
                this.selectDialogInputValue = "";
                this.selectedIntervalList = [];
                //this.selectedIntervalValue = ""
            },
            returnList() {
                this.$router.push({path: "./marketSettlementStandard"})
            },
            save() {
                // 3.0
                // 计提节点拦截
                const calcNodeSum = this.calcNodeSum();
                if (calcNodeSum === 0) {
                    return false
                }
                if (calcNodeSum !== 100) {
                    this.$message.warning('计提比例总和不等于100%');
                    return false
                }
                // 计提基数拦截

                if (!this.dealRangeList[0].list.length) {
                    this.$message({
                        message: '请先选择区间标准！',
                        type: 'warning'
                    });
                    return false;
                }

                if (!this.extractBaseNum) {
                    this.$message({
                        message: '请先选择计提基数！',
                        type: 'warning'
                    });
                    return false;
                }

                let params = {
                    profitStandardId: this.resValue,
                    calculationNodeList: this.calcNodeList,
                    extractBaseNum: this.extractBaseNum,
                    list: []
                };
                for (let i = 0; i < this.dealRangeList.length; i++) {
                    let item = this.dealRangeList[i];
                    for (let j = 0; j < item.list.length; j++) {
                        let subItem = item.list[j];
                        if (subItem.calculateExtractProportion) {
                            if (subItem.calculateExtractProportion < 0 || subItem.calculateExtractProportion > 100) {
                                this.$message({
                                    message: '计提比例必须大于0小于100！',
                                    type: 'warning'
                                });
                                return false;
                            }
                            params.list.push({
                                profitStandardId: this.resValue,
                                profitStandardDetailId: subItem.id,
                                calculateExtractProportion: subItem.calculateExtractProportion
                            })
                        } else {
                            this.$message({
                                message: '请把所有计提比例填写完成再保存！',
                                type: 'warning'
                            });
                            return false;
                        }
                    }
                }

                this.axios.post(api.marketSettlementStandardAddStandard, params).then((res) => {
                    if (res.data.code === 200) {
                        this.$message({
                            message: this.typeMap[this.type] + "成功",
                            type: 'success'
                        });
                        this.returnList();
                    }
                })
            },
            getSingleTransactionSettlement(id) {
                this.axios.post(api.marketSettlementStandardGetById, {id: id}).then((res) => {
                    const data = res.data.data;
                    //console.log(data);
                    this.extractBaseNum = data.extractBaseNum;
                    this.selectedIntervalValue = data.profitStandardId;
                    this.resValue = this.selectedIntervalValue;
                    this.calcNodeList = data.calculationNodeList;
                    data.detailVos.forEach((item) => {
                        this.dealRangeList[item.labelType - 1].list.push(item)
                    })
                })
            },

            // 3.0

            rewireCalcNode(value, index) {
                setTimeout(() => {
                    this.$set(this.calcNodeList[index], 'calculateProportion', this.formatTwoDecimal(value, 100))
                }, 30)
            },
            calcNodeSum() {
                let calcSum = 0;
                for (let i = 0; i < this.calcNodeList.length; i++) {
                    let item = this.calcNodeList[i]
                    if (!item.calculateNode) {
                        this.$message.warning('有计提节点未选择');
                        return 0
                    }
                    if (item.calculateProportion === '') {
                        this.$message.warning('有计提比例未设置');
                        return 0
                    }
                    if (Number(item.calculateProportion) === 0) {
                        this.$message.warning('计提比例不能设置为0');
                        return 0
                    }
                    calcSum += Number(item.calculateProportion)
                }
                return calcSum
            },

            addCalcNode() {
                // 先判断长度
                if (this.calcNodeList.length >= this.calcNodeOptions.length) {
                    this.$message.warning("不能再添加计提节点了")
                    return false;
                }
                const calcNodeSum = this.calcNodeSum()
                // calcNodeSum=0 直接拦截
                if (calcNodeSum === 0) {
                    return false
                }
                if (calcNodeSum >= 100) {
                    this.$message.warning("计提节点总和不能大于100%")
                    return false;
                } else {
                    this.calcNodeList.push({
                        calculateNode: "",
                        calculateProportion: ''
                    })
                }
            },
            removeCalcNode(index) {
                if (this.calcNodeList.length <= 1) {
                    this.$message.warning("请至少设置一个计提节点")
                    return false
                }
                this.calcNodeList.splice(index, 1)
            }

        },
        components: {},
        computed: {}
    }
</script>

<style scoped lang="stylus">
    .marketSettlementStandardHandle {
        .levelList {
            display: flex;
            flex-flow: wrap;
        }

        .levelList-item {
            width: 500px;
            margin-top: 30px;

            &:first-child {
                margin-right: 30px;
            }

            h3 {
                a {
                    margin-left 40px;
                    font-size: 14px;
                    color: #f00;
                }
            }
        }

        .selectedInterval-item {
            padding: 0 20px;
            position: relative;
            label {
                display: flex;
                align-items: center;

                > span {
                    display: inline-block;
                    margin-top: 20px;
                }
            }
            .selectedInterval-item-row {
                line-height: 25px;
            }
            .viewDetail {
                position: absolute;
                right: 0;
                top: 50%;
                margin-top: -20px;
            }
        }

    }

    // 3.0
    .calc-node-list {
        display: inline-block;
        position: relative;
        vertical-align: middle;
        margin: 0;
        padding: 0;
        li {
            position: relative;
            border: 1px solid #ccc;
            margin: 0 30px 30px 0;
            border-radius: 4px;
            padding: 15px;
            display: inline-block;
        }
        .calc-node-close {
            background-color: #fff;
            position: absolute;
            right: -15px;
            top: -15px;
            font-size: 30px;
            cursor: pointer;
        }
        .calc-node-add {
            margin-top: -30px;
            padding: 0;
            border: none;
            vertical-align: middle;
            font-size: 30px;
            cursor: pointer;
        }
    }


</style>






